package com.huawei.bdsolution.loadsmetric.util;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.SocketConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component
@PropertySource("${SPRING_CONFIG_LOCATION}")
public class HttpUtil implements DisposableBean {

    @Value("${http.connection.timeout:5000}")
    private int httpConnectionTimeout;

    @Value("${http.socket.timeout:5000}")
    private int httpSocketTimeout;

    @Value("${http.connection.request.timeout:5000}")
    private int httpConnectionRequestTimeout;

    @Value("${http.connection.max.total:100}")
    private int httpConnectionMaxTotal;

    @Value("${http.connection.max.per.route:5}")
    private int httpConnectionMaxPerRoute;

    private final PoolingHttpClientConnectionManager
            connectionManager = new PoolingHttpClientConnectionManager();
    private CloseableHttpClient httpClient;


    private void initHttpClient() {
        SocketConfig socketConfig = SocketConfig.custom()
                .setSoKeepAlive(true)
                .build();
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(httpConnectionTimeout)
                .setSocketTimeout(httpSocketTimeout)
                .setConnectionRequestTimeout(httpConnectionRequestTimeout)
                .build();
        connectionManager.setDefaultSocketConfig(socketConfig);
        connectionManager.setMaxTotal(httpConnectionMaxTotal);
        connectionManager.setDefaultMaxPerRoute(httpConnectionMaxPerRoute);
        httpClient = HttpClients.custom()
                .setConnectionManager(connectionManager)
                .setDefaultRequestConfig(requestConfig)
                .build();
    }

    public synchronized CloseableHttpClient createHttpClient(int workersNum) {
        if (httpClient == null) {
            httpConnectionMaxTotal = Math.max(httpConnectionMaxTotal, workersNum);
            initHttpClient();
        }
        return httpClient;
    }

    @Override
    public void destroy() {
        connectionManager.close();
    }
}
